package com.yx.learn.service.impl;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yx.learn.dao.DepartmentDao;
import com.yx.learn.domain.Department;
import com.yx.learn.service.DepartmentService;
import com.yx.learn.util.TreeAndToJsonUtil;

@Service("departmentService")
@Transactional
public class DepartmentServiceImpl implements DepartmentService {

	@Autowired
	@Qualifier("departmentDao")
	public DepartmentDao departmentDao;

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public JSONArray getAlistJson(int id) throws Exception{
		// TODO Auto-generated method stub

		TreeAndToJsonUtil js = new TreeAndToJsonUtil();
		JSONArray ja = new JSONArray();
		List<Department> list = departmentDao.getChildren(id);
		for (int i = 0; i < list.size(); i++) {
			Boolean hasChildren = false;
			if (departmentDao.getChildren(list.get(i).getId()).size() > 0) {
				hasChildren = true;
			}
			JSONObject jsonObject = js.departmentToJsonObject(list.get(i), hasChildren);
			ja.add(jsonObject);
		}
		return ja;
	}

	public void saveDepartment(Department department) throws Exception{
		// TODO Auto-generated method stub
		departmentDao.save(department);
	}

	public void updateDepartment(Department department) throws Exception{
		// TODO Auto-generated method stub
		departmentDao.update(department);
	}

	public void deleteDepartment(Department department) throws Exception{
		// TODO Auto-generated method stub
		departmentDao.delete(department);
	}
	
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public JSONArray getConditionAListJson(String name,String flag) throws Exception{
		// TODO Auto-generated method stub

		return null;
	}

	public Department findById(int id) throws Exception{
		// TODO Auto-generated method stub
		return departmentDao.findById(id);
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public String departmentsToCombobox() throws Exception{
		// TODO Auto-generated method stub
		List<Department> departments =  this.departmentDao.findAll();
		JSONArray ja = new JSONArray();
		for(int i=0;i<departments.size();i++){
			JSONObject jo = new JSONObject();
			jo.put("id", departments.get(i).getId());
			jo.put("deptName", departments.get(i).getDeptName());
			ja.add(jo);
		}
		String json = ja.toString();
		return json;
	}
}

